import type { RouteRecordRaw } from 'vue-router'

import router from '@/router'
import menu from '@/router/main/system/menu/menu'

function loadLocalFiles() {
  const localRouter: RouteRecordRaw[] = []
  // 1.读取main中所有的ts文件
  // vite自带的批量导入语法 eager表示是否立刻加载文件,默认是懒加载
  const files: Record<string, any> = import.meta.glob('../router/main/**/*.ts', {
    eager: true
  })

  // 2.存储导入的文件
  for (const key in files) {
    const module = files[key]
    localRouter.push(module.default)
  }
  return localRouter
}
export let firstMent: any = null
export default function mapMenuToRoutes(menuTree: any[]) {
  const localRouter = loadLocalFiles()

  const routes: RouteRecordRaw[] = []
  // 开始添加动态路由
  for (const menu of menuTree) {
    for (const subMenu of menu.children) {
      const route = localRouter.find((item) => item.path === subMenu.url)
      if (route) {
        // 给route的顶层惨淡添加路由重定向功能(但是只需要添加一次),直接添加会导致一级路由的重复添加
        if (!routes.find((item) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        // 添加菜单的二级路由
        routes.push(route)
      }
      if (!firstMent && route) {
        firstMent = subMenu
      }
    }
  }
  return routes
}

/**
 * // 将路由菜单映射为面包屑的导航
 * @param path
 * @param userMenu
 * @returns
 */
export function mapMenuToBread(path: string, userMenu: any[]) {
  const breadcrumbs: any[] = []
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrumbs.push({ name: menu.name, path: menu.url })
        breadcrumbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumbs
}

export function mapMenuListToIds(menuList: any[]) {
  const ids: number[] = []

  function recurseGetId(menus: any[]) {
    for (const item of menus) {
      if (item.children) {
        recurseGetId(item.children)
      } else {
        ids.push(item.id)
      }
    }
  }
  recurseGetId(menuList)

  return ids
}

// 从菜单中获取按钮权限
export function mapMenuListToPermissions(menuListTree: any[]) {
  const permissions: string[] = []

  function getPermissions(menuListTree: any[]) {
    for (const item of menuListTree) {
      if (item.type === 3) {
        permissions.push(item.permission)
      } else {
        getPermissions(item.children ?? [])
      }
    }
  }
  getPermissions(menuListTree)
  return permissions
}
